package com.medusa.aps.business.common.web;

import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter;
import com.alibaba.fastjson2.support.spring6.webservlet.view.FastJsonJsonView;
import com.medusa.aps.business.common.fastjson2.FastJson2;
import com.medusa.aps.business.common.fastjson2.filter.DesensitizeValueFilter;
import com.medusa.aps.business.common.web.converter.CodecGenericConverter;
import com.medusa.aps.business.common.web.converter.EnumConverterFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author 张治保
 * date 2023/4/6
 */
@EnableWebMvc
public class FastJson2MvcAdapter implements WebMvcConfigurer {

    FastJsonConfig config = new FastJsonConfig();

    {
        config.setDateFormat(FastJson2.DATETIME_PATTEN);
        config.setReaderFeatures(ArrayUtil.append(FastJson2.readFeature(), JSONReader.Feature.TrimString));
        config.setWriterFeatures(ArrayUtil.append(FastJson2.writeFeature(), JSONWriter.Feature.BrowserCompatible));
        config.setWriterFilters(DesensitizeValueFilter.INSTANCE);
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(StandardCharsets.UTF_8);
        converters.add(0, converter);
        converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        FastJsonJsonView fastJsonJsonView = new FastJsonJsonView();
        fastJsonJsonView.setFastJsonConfig(config);
        registry.enableContentNegotiation(fastJsonJsonView);
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverterFactory(EnumConverterFactory.INSTANCE);
        registry.addConverter(new CodecGenericConverter());
    }
}

